package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.GenDocDAO;
import mwa.cs.dao.RcTransDDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.RequestQuoteDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.RcTransD;
import mwa.cs.model.RcTransM;
import mwa.cs.model.Request;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS52000Srvl
 */
public class CS52000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS52000Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }


	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("methodType");
		if (vaProcessType.equals("getData")){
			getData(request, response);
		} else {
			saveData(request, response);
		}
	}
    
    @SuppressWarnings("unchecked")
	public void saveData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	    	
    	PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
		GenDocDAO voGenDocDAO = new GenDocDAO(db);
		RequestDAO voRequestDAO = new RequestDAO(db);
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		RcTransDDAO voRcTransDDAO = new RcTransDDAO(db);
		
		Request voRequest = new Request();
		RcTransM voRcTransM = new RcTransM();
		RcTransD voRcTransD = new RcTransD();
		String vaRequestNumber = request.getParameter("requestNumber");
		String vaAccount = request.getParameter("account").trim();
		String vaNamePay = request.getParameter("namePay").trim();
		String vaAddressPay = request.getParameter("addressPay").trim();
		String vaNetAmount = request.getParameter("netAmount").replace(",", "");
		String vaVatAmount = request.getParameter("vatAmount").replace(",", "");
		String vaGrossAmount = request.getParameter("grossAmount").replace(",", "");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		String vaSerialNumber = voGenDocDAO.generatingNextSNDoc(vnSiteId, JDate.getMonth(), JDate.getYear());
		
		// set ค่า Request
		if (voRequestDAO.getRequestType(vnSiteId, vaRequestNumber).equals("01")) {
			voRequest.setVaAccount(voGenDocDAO.generatingNextCRDoc(vnSiteId, JDate.getMonth(), JDate.getYear()));
		}
		voRequest.setVaStatus("2");
		voRequest.setVnUpdateUserId(vnUserId);
		voRequest.setVaUpdateDate(vaDate);
		voRequest.setVaUpdateTime(vaTime);
		voRequest.setVnSiteId(vnSiteId);
		voRequest.setVaRequestNumber(vaRequestNumber);
		
    	// Check Back Time 
		// Check Back Time 
		String vaReceiveTimeToDB = JDate.getTime();
		String vaReceiveDateToDB = JDate.checkBackTimeDate(vnSiteId);	
		
		// set ค่า RcTransM
		voRcTransM.setVnSiteId(vnSiteId);
		voRcTransM.setVnSerialNumber(Long.parseLong(vaSerialNumber));
		voRcTransM.setVaAccount(vaAccount);
		voRcTransM.setVaPayerName(vaNamePay);
		voRcTransM.setVaPayerAddress(vaAddressPay);
		voRcTransM.setVaReceiveDate(vaReceiveDateToDB);
		voRcTransM.setVaReceiveTime(vaReceiveTimeToDB);
		voRcTransM.setVnReceiveEmployee(vnUserId);
		voRcTransM.setVnNetAmount(Double.parseDouble(vaNetAmount));
		voRcTransM.setVnVatAmount(Double.parseDouble(vaVatAmount));
		voRcTransM.setVnGrossAmount(Double.parseDouble(vaGrossAmount));
		voRcTransM.setVnInsertUserId(vnUserId);
		voRcTransM.setVaInsertDate(vaDate);
		voRcTransM.setVaInsertTime(vaTime);
		voRcTransM.setVnUpdateUserId(0);
		
		// set ค่า RcTransD
		voRcTransD.setVnSiteId(vnSiteId);
		voRcTransD.setVnSerialNumber(Long.parseLong(vaSerialNumber));
		voRcTransD.setVaBillNumber(vaRequestNumber);
		voRcTransD.setVnWasteWaterCharge(0);
		voRcTransD.setVnGarbageCharge(0);
		voRcTransD.setVnOtherCharge(0);
		voRcTransD.setVnInsertUserId(vnUserId);
		voRcTransD.setVaInsertDate(vaDate);
		voRcTransD.setVaInsertTime(vaTime);
		voRcTransD.setVnUpdateUserId(0);
		
		try {
			db.beginTransaction();
			boolean vbResult = false;
			if (voRequestDAO.getRequestType(vnSiteId, vaRequestNumber).equals("01")) {
				vbResult = voRequestDAO.updateRequestForReceiveOther(voRequest);
			} else {
				vbResult = voRequestDAO.updateRequestForReceiveOtherNotNewWater(voRequest);
			}
			if (vbResult) {
				vbResult = voRcTransMDAO.insertRcTransMForReceiveOther(voRcTransM);
				if (vbResult) {
					vbResult = voRcTransDDAO.insertRcTransDForReceiveOther(voRcTransD, vaRequestNumber);
					if (vbResult) {
						voObject.put("message", "success");
						db.commit();
					} else {
						voObject.put("message", "fail");
					}
				} else {
					voObject.put("message", "fail");
				}
			} else {
				voObject.put("message", "fail");
			}
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS52000", JDate.getDate(), JDate.getTime(),vnUserId, "CS52000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			voObject.put("message", "fail");
		} finally {
			db.close();
		}
		voOut.print(voObject.toJSONString());
    }
    
    @SuppressWarnings("unchecked")
	public void getData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
    	RequestDAO voRequestDAO = new RequestDAO(db);
    	RequestQuoteDAO voRequestQuoteDAO = new RequestQuoteDAO(db);
    	AddressDAO voAddressDAO = new AddressDAO(db);
		String vaPutRequestNumber = request.getParameter("requestNumber");
		String vaRequestNumber = "";
		String vaMeterSerialNumber = "";
		String vaAccount2 = "";
		String vaInsertDate = "";
		String vaFullName = "";
		String vaRequestType = "";
		String vaHomeNumber = "";
		String vaAddress = "";
		String vaCity = "";
		String vaDistrict = "";
		String vaProvince = "";
		String vaPostCode = "";
		String vaTelephone = "";
		String vaStatus = "";
		JSONArray voDescription = new JSONArray();
		JSONArray voReceiveAmount = new JSONArray();
		JSONArray voVatAmount = new JSONArray();
		JSONArray voTotalAmount = new JSONArray();
		
		List<Map<String, Object>> voArrayList = null;
		Map<String, Object> voMapRequest = new HashMap<String, Object>();
		Map<String, Object> voMapRequestQuote = new HashMap<String, Object>();
		voMapRequest = voRequestDAO.getRequestForReceiveOther(vnSiteId, vaPutRequestNumber);
    	if (voMapRequest == null) {
    		voObject.put("message", "resultNull");
    	} else {
    		vaStatus = ""+ voMapRequest.get("STATUS");
    		if (vaStatus.equals("1")) {
    			voArrayList = voRequestQuoteDAO.searchRequestQuoteForReceiveOther(vnSiteId, vaPutRequestNumber);
    			if (voArrayList.size() > 0) {
    				for (int i = 0; i < voArrayList.size(); i++) {
    					voMapRequestQuote = voArrayList.get(i);	
						voDescription.add(voMapRequestQuote.get("DESCRIPTION"));
						voReceiveAmount.add(voMapRequestQuote.get("RECEIVE_AMOUNT"));
						voVatAmount.add(voMapRequestQuote.get("VAT_AMOUNT"));
						voTotalAmount.add(voMapRequestQuote.get("TOTAL_AMOUNT"));
					}
    				vaRequestNumber = ""+ voMapRequest.get("REQUEST_NUMBER");
    				vaMeterSerialNumber = ""+ voMapRequest.get("METER_SERIAL_NUMBER");
    				vaAccount2 = ""+ voMapRequest.get("ACCOUNT");
    				vaInsertDate = "" + voMapRequest.get("INSERT_DATE");
    				vaFullName = "" + voMapRequest.get("FULL_NAME");
    				vaHomeNumber = "" + voMapRequest.get("HOME_NUMBER");
    				vaAddress = "" + voMapRequest.get("ADDRESS");
    				vaCity = voAddressDAO.getCityName(""+ voMapRequest.get("PROVINCE_CODE"), ""+ voMapRequest.get("DISTRICT_CODE"), ""+ voMapRequest.get("CITY_CODE"));
			    	vaDistrict = voAddressDAO.getDistrictName(""+ voMapRequest.get("PROVINCE_CODE"), ""+ voMapRequest.get("DISTRICT_CODE"));
			    	vaProvince = voAddressDAO.getProvinceName(""+ voMapRequest.get("PROVINCE_CODE"));
    				vaPostCode = "" + voMapRequest.get("POST_CODE");
    				vaTelephone = "" + voMapRequest.get("TELEPHONE");
    				vaRequestType = "" + voMapRequest.get("REQUEST_DESCRIPTION");
			    	
			    	voObject.put("requestNumber", vaRequestNumber);
					voObject.put("meterSerialNumber", vaMeterSerialNumber);
					voObject.put("account", vaAccount2);
					voObject.put("fullName", vaFullName);
					voObject.put("homeNumber", vaHomeNumber);
					voObject.put("address", vaAddress);
					voObject.put("city", vaCity);
					voObject.put("district", vaDistrict);
					voObject.put("province", vaProvince);
					voObject.put("postCode", vaPostCode);
					voObject.put("telephone", vaTelephone);
					voObject.put("insertDate", vaInsertDate);
					voObject.put("requestType", vaRequestType);
					voObject.put("description", voDescription);
					voObject.put("receiveAmount", voReceiveAmount);
					voObject.put("vatAmount", voVatAmount);
					voObject.put("totalAmount", voTotalAmount);
    			} else {
    				voObject.put("message", "status1");
    			}
    		} else if (vaStatus.equals("2")) {
    			voObject.put("message", "status2");
    		} else if (vaStatus.equals("3")) {
    			voObject.put("message", "status3");
    		} else if (vaStatus.equals("4")){
    			voObject.put("message", "status4");
    		}
    	}
    	db.close();
    	voOut.print(voObject.toJSONString());
	}
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
